
from rest_framework import serializers
from apps.common.base.serializers import BaseSerializer
from apps.chat.conversation.models import Conversation
from apps.chat.message.dao import MessageDao


class ConversationBaseSerializer(BaseSerializer):

    class Meta:
        model = Conversation
        fields = "__all__"
class ConversationListSerializer(BaseSerializer):

    unreadCount = serializers.SerializerMethodField()
    def get_unreadCount(self, obj):
        user = self.context["request"].user
        try:
            return obj.conversationId_message.all().filter(isRead=False).exclude(befrom=user).count()
        except:
            return 0

    userInfo = serializers.SerializerMethodField()
    def get_userInfo(self, obj):
        user = self.context["request"].user
        if obj.userA == user:
            if obj.userB:
                data = {'id': obj.userB.id, 'nickname': obj.userB.nickname}
                data['avatarUrl'] = obj.userB.avatarUrl
                return data
            else:
                return {}

        elif obj.userB == user:
            if obj.userA:
                data = {'id': obj.userA.id, 'nickname': obj.userA.nickname}
                data['avatarUrl'] = obj.userA.avatarUrl
                return data
            else:
                return {}
        else:
            return {}
            
    lastMessage = serializers.SerializerMethodField()
    def get_lastMessage(self, obj):
        if obj.lastMessage:
            message = {'id': obj.lastMessage.id, 'createTime': str(obj.lastMessage.createTime) }
            if obj.lastMessage.contentType == 'image':
                message['content'] = "[图片]"
            elif obj.lastMessage.contentType == 'anotherPay':
                message['content'] = "[代付]已发起代付"
            else:
                message['content'] = obj.lastMessage.content
            return message
        else:
            return {}

    class Meta:
        model = Conversation
        fields = "__all__"

class ConversationModelSerializer(ConversationListSerializer):

    class Meta:
        model = Conversation
        fields = "__all__"